
package com.jiu.bean;

import java.awt.Color;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.log4j.Logger;
import com.jiu.core.FishClient;
import com.jiu.http.webqq.Message;
import com.jiu.http.webqq.QQHttp;
import com.jiu.http.webqq.Result;
import com.jiu.util.JSONUtils;
import com.jiu.util.UnicodeUtils;

public class QQThread extends Thread {
	private Logger log = Logger.getLogger(QQThread.class);
	private FishClient context;	
	private QQHttp qqHttp;
	public QQThread(FishClient context) {
		this.context = context;
		this.setName("QQ-Thread");
	}
	
	@Override
	public void run() {
		this.qqHttp = new QQHttp(context);
		String reciveJson = "";
		while(true){
			try {
				Thread.sleep(1000);
				reciveJson = UnicodeUtils.decodeUnicode(qqHttp.webQQpoll2());
				if(reciveJson.contains("xml"))continue;
				Message message = new Message(JSONUtils.parseMap(reciveJson));
				if(message.getRetcode()==116){
					qqHttp.getSession().setPtwebqq(message.getP());
					qqHttp.updatePtwebqq();
					log.debug("成功更新ptwebqq:"+message.getP());					
				}else if(message.getRetcode()==121||message.getRetcode()==103){
					this.qqHttp = new QQHttp(context);
				}else if(message.getRetcode()!=0){
					log.debug(reciveJson);					
				}
				//这里是接收的所有消息	
				for(Result r:message.getResult()){
					String msg = r.getText();
					if(r.getGroupCode().equals(qqHttp.getGroup_code())){
						/**监控群命令*/
						Pattern pattern = Pattern.compile("\\w{4,5}( \\w{1,10}){1,2}");//#[Dd][\\w]{1}  [?]=[\\w]{1}
					    Matcher matcher = pattern.matcher(msg);
						if(matcher.find()){    					
							String cmdstr = matcher.group();
							String[]cmds = cmdstr.split(" ");
							if(cmds[1].equals(context.getAccount().getQq())||"all".equalsIgnoreCase(cmds[1])){
								context.displayMessage(format(new Date())+"：收到控制指令："+cmdstr,new Color(255,156,18));
								String sendMsg = "命令集:【find|sleep|start|stop|exit|time|color|size|inall】";
								if(cmds[0].equalsIgnoreCase("sleep")){
									int t = 3600;
									if(cmds.length==3){
										t = Integer.parseInt(cmds[2]);
									}
									context.getAccount().setStopTime(System.currentTimeMillis()+1000*t);        							
									sendMsg = "机器人将于"+format(context.getAccount().getStopTime())+"进入睡眠，Start命令可唤醒！";
								}else if(cmds[0].equalsIgnoreCase("start")){
									if(context.getAccount().isStop()){
										//停止状态的才启动
										sendMsg = "小玩应已启动！";
										context.updateStatus(false);
										context.getSendMap().put(1, "#D"+new Random().nextInt(10)); 
										context.getAccount().setStopTime(System.currentTimeMillis()*2);
									}else{
										sendMsg = "正常工作中。。。";
									}
								}else if(cmds[0].equalsIgnoreCase("stop")){
									if(context.getAccount().isStop()){
										sendMsg = "早就停止工作了。。";
									}else{
										context.updateStatus(true);
										sendMsg = "小玩应即将暂停。。！";
									}
								}else if(cmds[0].equalsIgnoreCase("exit")){																
									context.updateStatus(true); 										
									System.exit(0);  
								}else if(cmds[0].equalsIgnoreCase("time")){
									if(cmds.length>2)
										context.getAccount().setTime(Integer.parseInt(cmds[2])<25?25:Integer.parseInt(cmds[2]));
									sendMsg = "钓鱼时间间隔设置为"+context.getAccount().getTime()+"秒！";
								}else if(cmds[0].equalsIgnoreCase("find")){
									sendMsg = context.getAccount().getNickname()+" 状态："+(context.getAccount().isStop()?"暂停中！":"运行中！")+"间隔:"+context.getAccount().getTime()+"+(0~4)秒"
											+ "\\\\n睡眠："+format(context.getAccount().getStopTime());
								}else if(cmds[0].equalsIgnoreCase("inall")){
									if(cmds.length>2)
										context.getAccount().setInAll(Integer.parseInt(cmds[2])<3?3:Integer.parseInt(cmds[2]));
									sendMsg = "【in all】 间隔，每"+context.getAccount().getInAll()+"次卖鱼触发一次";
								}
								sendMsg(sendMsg);
							}    			
						}
						/**
						 * 指定命令
						 * */
						pattern = Pattern.compile("^@"+context.getAccount().getNickname()+"\\s*(#[Dd].*)");
						matcher = pattern.matcher(msg);
						if(matcher.find()){
							if(matcher.group(1).contains("pm")){//自己
								sendMsg(parseFishInfoList(context.getFishHttpService().getFishAuction("1")));
							}else if(matcher.group(1).contains("PM")){
								sendMsg(parseFishInfoList(context.getFishHttpService().getFishAuction("0")));
							}else if(matcher.group(1).contains("bag")||matcher.group(1).contains("BAG")){
								sendMsg(parseFishInfoList(context.getFishHttpService().getFishBag()));
							}else if(matcher.group(1).contains("me")||matcher.group(1).contains("ME")){
								sendMsg(parseFishInfoList(context.getFishHttpService().getFishMyDetail()));
							}else{
								context.getSendMap().put(5, matcher.group(1));
								context.displayMessage("收到命令指令："+matcher.group(1).replace("\\s", ""),new Color(255,156,18));								
							}
						
						}
					}
			
				}
			
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
		private String parseFishInfoList(List<Map<String, Object>> list) {
			StringBuffer infos = new StringBuffer();
			for(Map<String,Object> map:list){
				infos.append(map.get("msg").toString().replace("\n", ""));
			}
		return infos.toString();
	}

		public void sendMsg(String msg){
			try {
				if(qqHttp!=null)
					qqHttp.sendMessage(msg);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		private String format(Date date){
			DateFormat fmt = new SimpleDateFormat("HH:mm:ss");
			return fmt.format(date);
		}
		private String format(long time){
			DateFormat fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm");
			return fmt.format(new Date(time));
		}
}
